package com.shisfish.library.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import com.shisfish.library.Impl.BookSingleImpl;
import com.shisfish.library.Impl.ErrorInfoImpl;
import com.shisfish.library.Model.ErrorInfo;
import com.shisfish.library.Prere.Login;
import com.shisfish.library.Utils.Global.GlobalVariable;
import com.shisfish.library.Utils.Global.toJsonUtils;
import com.shisfish.library.Utils.PageModel.Page;
import com.shisfish.library.Utils.PageModel.PageUtils;

@Path("errorInfo")
public class ErrorInfoController extends GlobalVariable {

	private ErrorInfoImpl errorInfoImpl = new ErrorInfoImpl();
	
	@POST
	@Path("insertAErrorInfo/{idadmin}/{type}")
	@Produces("application/json; charset=utf-8")
	public String insertAErrorInfo(@PathParam("idadmin") String idadmin, @PathParam("type") int type, 
			@FormParam("barCode") String barCode,  
			@Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginAdmin(idadmin, request)) {
			
			List<Map<String, Object>> bookSingles = new BookSingleImpl().selectByBarCode(barCode);
			if (bookSingles.size() > 0) {
				String isbn = (String) bookSingles.get(0).get("isbn");
				ErrorInfo errorInfo = new ErrorInfo(barCode, type, isbn);
				
				int flag = errorInfoImpl.insertOne(errorInfo);
				if (flag == 1) {
					globalMap.put(STATUS_CODE, SUCCESS);
				} else {
					globalMap.put(STATUS_CODE, INSERT_WR);
				}
			} else {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			}
			
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@GET
	@Path("selectByPage/{type}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String selectByPage(@PathParam("type") int type, @PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		int count = errorInfoImpl.countByType(type);
		
		if (count > 0) {
			
			Page page = PageUtils.createPage(count, currentPage, pageSize);
			List<Map<String, Object>> errorInfos = errorInfoImpl.selectByTypePage(type, page.getBeginIndex(), pageSize);
			
			if (errorInfos.size() > 0) {
				globalMap.put("list", errorInfos);
				globalMap.put("page", page);
				globalMap.put(STATUS_CODE, SUCCESS);
			} else if (errorInfos.size() == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
			
		} else if (count == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		} else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	
}
